package com.deep.bilibili.interceptor;

import com.deep.bilibili.dto.AdminerDto;
import com.deep.bilibili.service.AdminerService;
import com.deep.bilibili.service.MenuService;
import com.deep.bilibili.util.SpringUtil;
import com.deep.bilibili.vo.TreeMenu;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
import java.util.List;
import java.util.Optional;

public class GlobalInterceptor implements HandlerInterceptor {
    private static Logger logger = LoggerFactory.getLogger(GlobalInterceptor.class);



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //
        if (handler instanceof HandlerMethod) {

            /**
             * 保存登录信息
             */
            Principal principal = request.getUserPrincipal();
            logger.info("principal = {}", principal);

            /**
             * 获取当前用户的菜单
             */
            if (Optional.ofNullable(principal).isPresent()) {
                String username = principal.getName();
                AdminerDto adminerDto = SpringUtil.getBean(AdminerService.class).getUserByName(username);
                Integer adminerId = adminerDto.getId();
                List<TreeMenu> treeMenus = SpringUtil.getBean(MenuService.class).selectTreeMenuByAdminerId(adminerId);
                request.setAttribute("treeMenus", treeMenus);
            }

            /**
             * 资源和当前选中菜单
             */
            String res = request.getParameter("p");
            if (StringUtils.isNotBlank(res)) {
                request.getSession().setAttribute("res", res);
            }
            String cur = request.getParameter("t");
//        String par = "";
            if (StringUtils.isNotBlank(cur)) {
                request.getSession().setAttribute("cur", cur);
//            Menu menu = SpringUtil.getBean(MenuMapper.class).findById(Integer.valueOf(cur));
//            par = String.valueOf(menu.getPid());
            }

        }
        return true;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
//                           ModelAndView modelAndView) throws Exception {
//        if (Optional.ofNullable(modelAndView).isPresent()) {
//            // 防止出现空指针
//            // 在springboot中如果是错误页肯定不会出现mv为null的情况
//            if (StringUtils.isBlank(modelAndView.getViewName())) {
//                modelAndView.setViewName("error/common");
//            }
//            // 注意：该请求只是测试试用，并没有实际的意义
//        }
//    }

}
